package com.android.async;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.android.rest.vo.GeoName;
import com.google.gson.Gson;

public class GeoNamesService {

    private static final String GEONAME_RESTURL = "http://api.geonames.org/postalCodeSearchJSON?maxRows=4&username=demo&postalcode=";

    GeoNamesService() {

    }

    public List<GeoName> searchPostalCode(String code) {

        String url = GEONAME_RESTURL + code;
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                InputStream stream = entity.getContent();
                String responseString = convertStreamToString(stream);

                DataWrapper wrap = new DataWrapper();
                wrap = wrap.fromJson(responseString);
                return wrap.postalCodes;
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    private static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public class DataWrapper {
        public List<GeoName> postalCodes = null;

        public DataWrapper fromJson(String jsonString) {
            return new Gson().fromJson(jsonString, DataWrapper.class);
        }
    }
}